// DOM 元素缓存
const elements = {
  loginBtn: document.querySelector('.login-btn'),
  registerBtn: document.querySelector('.register-btn'),
  profileLoginBtn: document.querySelector('.profile-login'),
  collectionLoginBtn: document.querySelector('.collection-login'),
  historyLoginBtn: document.querySelector('.history-login'),
  loginModal: document.querySelector('.login-modal'),
  registerModal: document.querySelector('.register-modal'),
  closeLoginModal: document.querySelector('.login-modal .close-modal'),
  closeRegisterModal: document.querySelector('.register-modal .close-modal'),
  showRegister: document.querySelector('.show-register'),
  showLogin: document.querySelector('.show-login'),
  videoModal: document.querySelector('.video-modal'),
  closeVideoModal: document.querySelector('.video-modal .close-modal'),
  videoPlayer: document.getElementById('video-player'),
  videoTitle: document.getElementById('video-title'),
  videoLinks: document.querySelectorAll('.play-overlay'),
  socialLoginPopup: document.querySelector('.social-login-popup'),
  closePopup: document.querySelector('.close-popup'),
  socialIcons: document.querySelectorAll('.social-icon'),
  platformTabs: document.querySelectorAll('.platform-tabs .tab'),
  tabPanes: document.querySelectorAll('.tab-content .tab-pane'),
  sidebarMenu: document.querySelector('.sidebar-menu'),
  sidebarContent: document.getElementById('sidebar-content'),
  sidebarOverlay: document.querySelector('.sidebar-overlay'),
  closeSidebar: document.querySelector('.close-sidebar'),
  menuItems: document.querySelectorAll('.menu-item[data-menu]'),
  menuTitle: document.getElementById('menu-title'),
  otherLoginBtn: document.querySelector('.other-login-btn'),
  bottomNavItems: document.querySelectorAll('.bottom-nav .nav-item'),
  header: document.querySelector('header'),
  loginForm: document.getElementById('login-form'),
  registerForm: document.getElementById('register-form'),
  accountLoginBtns: document.querySelectorAll('.account-login'),
  logoutBtn: document.getElementById('logout-btn')
};

// 应用状态
const appState = {
  isLoggedIn: localStorage.getItem('isLoggedIn') === 'true',
  currentUser: null,
  activeMenu: null
};

// 显示登录模态框
function showLoginModal() {
  elements.loginModal.style.display = 'flex';
  document.body.style.overflow = 'hidden';
}

// 显示注册模态框
function showRegisterModal() {
  elements.registerModal.style.display = 'flex';
  document.body.style.overflow = 'hidden';
}

// 关闭模态框
function closeModal(modal) {
  modal.style.display = 'none';
  document.body.style.overflow = 'auto';
}

// 打开视频播放模态框
function openVideoModal(title, src) {
  elements.videoTitle.textContent = title;
  elements.videoPlayer.src = src;
  elements.videoModal.style.display = 'flex';
  document.body.style.overflow = 'hidden';
  elements.videoPlayer.play();
}

// 关闭视频播放模态框
function closeVideo() {
  elements.videoModal.style.display = 'none';
  document.body.style.overflow = 'auto';
  elements.videoPlayer.pause();
  elements.videoPlayer.src = '';
}

// 打开社交登录悬浮框
function openSocialLoginPopup(platform) {
  elements.socialLoginPopup.style.display = 'block';
  document.body.style.overflow = 'hidden';
  
  // 激活对应平台的标签页
  elements.platformTabs.forEach(tab => {
    if (tab.dataset.tab === platform) {
      tab.classList.add('active');
    } else {
      tab.classList.remove('active');
    }
  });
  
  // 显示对应平台的内容
  elements.tabPanes.forEach(pane => {
    if (pane.id === `${platform}-tab`) {
      pane.classList.add('active');
    } else {
      pane.classList.remove('active');
    }
  });
}

// 关闭社交登录悬浮框
function closeSocialLoginPopup() {
  elements.socialLoginPopup.style.display = 'none';
  document.body.style.overflow = 'auto';
}

// 打开侧边菜单
function openSidebar(menuType) {
  if (!appState.isLoggedIn) {
    showLoginModal();
    return;
  }
  
  // 更新菜单标题
  elements.menuTitle.textContent = getMenuTitle(menuType);
  
  // 生成菜单内容
  generateSidebarContent(menuType);
  
  // 显示侧边菜单和遮罩层
  elements.sidebarMenu.style.left = '0';
  elements.sidebarOverlay.style.display = 'block';
  document.body.style.overflow = 'hidden';
  
  // 更新应用状态
  appState.activeMenu = menuType;
}

// 关闭侧边菜单
function closeSidebarMenu() {
  elements.sidebarMenu.style.left = '-100%';
  elements.sidebarOverlay.style.display = 'none';
  document.body.style.overflow = 'auto';
  
  // 更新应用状态
  appState.activeMenu = null;
}

// 获取菜单标题
function getMenuTitle(menuType) {
  const titles = {
    favorites: '我的收藏',
    history: '观看历史',
    notifications: '消息通知',
    settings: '设置'
  };
  return titles[menuType] || '菜单';
}

// 生成侧边菜单内容
function generateSidebarContent(menuType) {
  elements.sidebarContent.innerHTML = '';
  
  switch(menuType) {
    case 'favorites':
      generateFavoritesContent();
      break;
    case 'history':
      generateHistoryContent();
      break;
    case 'notifications':
      generateNotificationsContent();
      break;
    case 'settings':
      generateSettingsContent();
      break;
    default:
      elements.sidebarContent.innerHTML = '<p>暂无内容</p>';
  }
}

// 生成收藏内容
function generateFavoritesContent() {
  // 模拟收藏数据
  const favorites = [
    { id: 1, title: '王者荣耀 - 英雄CG', image: 'images/lun1.png', duration: '03:45', time: '今天' },
    { id: 2, title: '和平精英 - 战场实录', image: 'images/lun2.png', duration: '05:12', time: '昨天' },
    { id: 3, title: '金铲铲之战 - 阵容搭配', image: 'images/lun3.png', duration: '07:30', time: '3天前' },
    { id: 4, title: '英雄联盟 - 全球总决赛', image: 'images/live3.png', duration: '12:15', time: '1周前' }
  ];
  
  let html = '';
  
  if (favorites.length > 0) {
    html = favorites.map(item => `
      <div class="sidebar-collection-item">
        <div class="sidebar-thumb">
          <img src="${item.image}" alt="${item.title}">
        </div>
        <div class="sidebar-info">
          <div class="sidebar-title">${item.title}</div>
          <div class="sidebar-meta">
            <span>${item.time}</span>
            <span class="sidebar-duration">${item.duration}</span>
          </div>
        </div>
      </div>
    `).join('');
  } else {
    html = '<p class="text-center text-gray-400 py-10">您还没有收藏任何内容</p>';
  }
  
  elements.sidebarContent.innerHTML = html;
}

// 生成历史记录内容
function generateHistoryContent() {
  // 模拟历史记录数据
  const histories = [
    { id: 1, title: '王者荣耀 - 新英雄预告', image: 'images/cg4.png', duration: '02:38', time: '刚刚', progress: 65 },
    { id: 2, title: '和平精英 - 新武器展示', image: 'images/cg7.png', duration: '01:56', time: '今天', progress: 100 },
    { id: 3, title: '金铲铲之战 - 最强阵容', image: 'images/cg11.png', duration: '03:12', time: '今天', progress: 30 },
    { id: 4, title: '英雄联盟 - 皮肤介绍', image: 'images/cg6.png', duration: '04:20', time: '昨天', progress: 75 }
  ];
  
  let html = '';
  
  if (histories.length > 0) {
    html = histories.map(item => `
      <div class="sidebar-history-item">
        <div class="sidebar-thumb relative">
          <img src="${item.image}" alt="${item.title}">
          ${item.progress < 100 ? `<div class="progress-bar" style="width: ${item.progress}%"></div>` : ''}
        </div>
        <div class="sidebar-info">
          <div class="sidebar-title">${item.title}</div>
          <div class="sidebar-meta">
            <span>${item.time}</span>
            <span class="sidebar-duration">${item.duration}</span>
          </div>
        </div>
      </div>
    `).join('');
  } else {
    html = '<p class="text-center text-gray-400 py-10">暂无观看历史</p>';
  }
  
  elements.sidebarContent.innerHTML = html;
}

// 生成消息通知内容
function generateNotificationsContent() {
  // 模拟消息通知数据
  const notifications = [
    { id: 1, title: "系统通知", content: "欢迎使用荣耀CG动画平台，新用户注册成功！", time: "刚刚", unread: true },
    { id: 2, title: "内容更新", content: "您关注的《王者荣耀》发布了新的英雄CG动画", time: "今天 10:25", unread: true },
    { id: 3, title: "活动提醒", content: "参与我们的评论活动，有机会获得游戏周边奖励！", time: "今天 09:12", unread: true },
    { id: 4, title: "互动消息", content: "用户@游戏爱好者 回复了您的评论", time: "昨天 18:30", unread: false },
    { id: 5, title: "系统通知", content: "平台将于本周日凌晨进行维护，预计维护时间2小时", time: "昨天 15:45", unread: false }
  ];
  
  let html = '';
  
  if (notifications.length > 0) {
    html = notifications.map(item => `
      <div class="notification-item ${item.unread ? 'unread' : ''}">
        <div class="notification-header">
          <div class="notification-title">${item.title}</div>
          <div class="notification-time">${item.time}</div>
        </div>
        <div class="notification-content">${item.content}</div>
      </div>
    `).join('');
  } else {
    html = '<p class="text-center text-gray-400 py-10">暂无消息通知</p>';
  }
  
  elements.sidebarContent.innerHTML = html;
}

// 生成设置内容
function generateSettingsContent() {
  const html = `
    <div class="menu-section">
      <h3 class="section-title">账号设置</h3>
      <div class="setting-item">
        <div class="setting-label">用户名</div>
        <div class="setting-value">游戏达人</div>
      </div>
      <div class="setting-item">
        <div class="setting-label">绑定手机</div>
        <div class="setting-value">138****6789</div>
      </div>
      <div class="setting-item">
        <div class="setting-label">绑定邮箱</div>
        <div class="setting-value">example@mail.com</div>
      </div>
      <div class="setting-item">
        <div class="setting-label">修改密码</div>
        <div class="text-red-500 cursor-pointer">点击修改</div>
      </div>
    </div>
    
    <div class="menu-section">
      <h3 class="section-title">通知设置</h3>
      <div class="setting-item">
        <div class="setting-label">新消息通知</div>
        <div class="setting-toggle active"></div>
      </div>
      <div class="setting-item">
        <div class="setting-label">内容更新提醒</div>
        <div class="setting-toggle active"></div>
      </div>
      <div class="setting-item">
        <div class="setting-label">活动通知</div>
        <div class="setting-toggle"></div>
      </div>
    </div>
    
    <div class="menu-section">
      <h3 class="section-title">应用设置</h3>
      <div class="setting-item">
        <div class="setting-label">自动播放</div>
        <div class="setting-toggle active"></div>
      </div>
      <div class="setting-item">
        <div class="setting-label">高清模式</div>
        <div class="setting-toggle"></div>
      </div>
      <div class="setting-item">
        <div class="setting-label">缓存大小</div>
        <div class="setting-value">128MB</div>
      </div>
      <div class="setting-item">
        <div class="setting-label">清除缓存</div>
        <div class="text-red-500 cursor-pointer">点击清除</div>
      </div>
    </div>
    
    <div class="menu-section">
      <button class="logout-btn" id="logout-btn">
        <i class="fa fa-sign-out"></i>
        <span>退出登录</span>
      </button>
    </div>
  `;
  
  elements.sidebarContent.innerHTML = html;
  
  // 添加退出登录按钮事件
  document.getElementById('logout-btn').addEventListener('click', logout);
}

// 退出登录
function logout() {
  // 清除用户信息
  localStorage.removeItem('isLoggedIn');
  appState.isLoggedIn = false;
  appState.currentUser = null;
  
  // 重置用户界面
  document.querySelector('.username').textContent = '游客用户';
  document.querySelector('.profile-avatar img').src = 'images/tou.jpg';
  document.querySelector('.user-desc').textContent = '欢迎来到个人中心，请登录以享受更多功能';
  
  // 重置统计数据
  document.querySelectorAll('.stat-value').forEach(el => {
    el.textContent = '0';
  });
  
  // 显示登录按钮
  document.querySelector('.profile-login').style.display = 'block';
  
  // 重置收藏和历史记录部分
  resetCollectionsAndHistory();
  
  // 关闭侧边菜单
  closeSidebarMenu();
  
  console.log('用户已退出登录');
}

// 重置收藏和历史记录部分
function resetCollectionsAndHistory() {
  // 重置收藏部分
  const collectionsContainer = document.querySelector('.my-collections .recommend-container');
  if (collectionsContainer) {
    collectionsContainer.parentNode.removeChild(collectionsContainer);
    
    const emptyState = document.createElement('div');
    emptyState.className = 'empty-state';
    emptyState.innerHTML = `
      <i class="fa fa-bookmark-o"></i>
      <p>您还没有收藏任何CG动画</p>
      <p>登录后可以收藏喜欢的内容</p>
      <button class="login-btn collection-login">立即登录</button>
    `;
    
    document.querySelector('.my-collections').appendChild(emptyState);
    
    // 重新绑定登录按钮事件
    document.querySelector('.collection-login').addEventListener('click', showLoginModal);
  }
  
  // 重置历史记录部分
  const historyContainer = document.querySelector('.watch-history .recommend-container');
  if (historyContainer) {
    historyContainer.parentNode.removeChild(historyContainer);
    
    const emptyState = document.createElement('div');
    emptyState.className = 'empty-state';
    emptyState.innerHTML = `
      <i class="fa fa-history"></i>
      <p>您还没有观看记录</p>
      <p>登录后可以保存观看历史</p>
      <button class="login-btn history-login">立即登录</button>
    `;
    
    document.querySelector('.watch-history').appendChild(emptyState);
    
    // 重新绑定登录按钮事件
    document.querySelector('.history-login').addEventListener('click', showLoginModal);
  }
}

// 更新用户界面为已登录状态
function updateUserProfile(username) {
  // 实际应用中，这里应该从服务器获取用户信息
  const userData = {
    username: username,
    avatar: 'images/tou.jpg',
    followers: 25,
    following: 18,
    favorites: 42
  };
  
  // 更新用户信息
  document.querySelector('.username').textContent = userData.username;
  document.querySelector('.profile-avatar img').src = userData.avatar;
  document.querySelector('.user-desc').textContent = '欢迎回来，一起探索更多精彩内容！';
  
  // 更新统计数据
  document.querySelectorAll('.stat-value')[0].textContent = userData.following;
  document.querySelectorAll('.stat-value')[1].textContent = userData.followers;
  document.querySelectorAll('.stat-value')[2].textContent = userData.favorites;
  
  // 隐藏登录按钮
  document.querySelector('.profile-login').style.display = 'none';
  
  // 更新收藏和历史记录部分
  updateCollectionsAndHistory();
  
  // 更新应用状态
  appState.isLoggedIn = true;
  appState.currentUser = userData;
  
  console.log('用户已登录:', username);
}

// 更新收藏和历史记录部分
function updateCollectionsAndHistory() {
  // 模拟收藏和历史记录数据
  const collections = [
    { id: 1, title: '王者荣耀 - 英雄CG', image: 'images/lun1.png', duration: '03:45' },
    { id: 2, title: '和平精英 - 战场实录', image: 'images/lun2.png', duration: '05:12' },
    { id: 3, title: '金铲铲之战 - 阵容搭配', image: 'images/lun3.png', duration: '07:30' }
  ];
  
  const history = [
    { id: 1, title: '王者荣耀 - 新英雄预告', image: 'images/cg4.png', duration: '02:38', progress: 65 },
    { id: 2, title: '和平精英 - 新武器展示', image: 'images/cg7.png', duration: '01:56', progress: 100 },
    { id: 3, title: '金铲铲之战 - 最强阵容', image: 'images/cg11.png', duration: '03:12', progress: 30 }
  ];
  
  // 更新收藏部分
  const collectionsContainer = document.querySelector('.my-collections .empty-state');
  if (collectionsContainer) {
    collectionsContainer.parentNode.removeChild(collectionsContainer);
    
    const newContainer = document.createElement('div');
    newContainer.className = 'recommend-container';
    
    collections.forEach(item => {
      const collectionItem = document.createElement('div');
      collectionItem.className = 'recommend-item';
      collectionItem.dataset.videoId = item.id;
      
      collectionItem.innerHTML = `
        <div class="video-thumb">
          <img src="${item.image}" alt="${item.title}">
          <div class="play-overlay">
            <i class="fa fa-play-circle"></i>
          </div>
          <span class="duration">${item.duration}</span>
        </div>
        <h3>${item.title}</h3>
        <p>收藏于 ${new Date().toLocaleDateString()}</p>
      `;
      
      newContainer.appendChild(collectionItem);
    });
    
    document.querySelector('.my-collections').appendChild(newContainer);
  }
  
  // 更新历史记录部分
  const historyContainer = document.querySelector('.watch-history .empty-state');
  if (historyContainer) {
    historyContainer.parentNode.removeChild(historyContainer);
    
    const newContainer = document.createElement('div');
    newContainer.className = 'recommend-container';
    
    history.forEach(item => {
      const historyItem = document.createElement('div');
      historyItem.className = 'recommend-item';
      historyItem.dataset.videoId = item.id;
      
      historyItem.innerHTML = `
        <div class="video-thumb">
          <img src="${item.image}" alt="${item.title}">
          <div class="play-overlay">
            <i class="fa fa-play-circle"></i>
          </div>
          <span class="duration">${item.duration}</span>
          ${item.progress < 100 ? `<div class="progress-bar" style="width: ${item.progress}%"></div>` : ''}
        </div>
        <h3>${item.title}</h3>
        <p>上次观看于 ${new Date().toLocaleTimeString()}</p>
      `;
      
      newContainer.appendChild(historyItem);
    });
    
    document.querySelector('.watch-history').appendChild(newContainer);
  }
  
  // 重新绑定视频播放事件
  document.querySelectorAll('.play-overlay').forEach(link => {
    link.addEventListener('click', function() {
      const title = this.closest('.recommend-item').querySelector('h3').textContent;
      const videoId = this.closest('.recommend-item').dataset.videoId;
      // 这里应该使用实际的视频路径
      const videoSrc = `videos/cg2.mp4`;
      openVideoModal(title, videoSrc);
    });
  });
}

// 初始化事件监听
function initEventListeners() {
  // 登录/注册模态框事件
  elements.loginBtn.addEventListener('click', showLoginModal);
  elements.registerBtn.addEventListener('click', showRegisterModal);
  elements.profileLoginBtn.addEventListener('click', showLoginModal);
  elements.collectionLoginBtn.addEventListener('click', showLoginModal);
  elements.historyLoginBtn.addEventListener('click', showLoginModal);
  
  elements.closeLoginModal.addEventListener('click', () => closeModal(elements.loginModal));
  elements.closeRegisterModal.addEventListener('click', () => closeModal(elements.registerModal));
  
  elements.showRegister.addEventListener('click', () => {
    closeModal(elements.loginModal);
    showRegisterModal();
  });
  
  elements.showLogin.addEventListener('click', () => {
    closeModal(elements.registerModal);
    showLoginModal();
  });
  
  // 视频播放事件
  elements.videoLinks.forEach(link => {
    link.addEventListener('click', function() {
      const title = this.closest('.recommend-item').querySelector('h3').textContent;
      const videoId = this.closest('.recommend-item').dataset.videoId;
      // 这里应该使用实际的视频路径
      const videoSrc = `videos/cg1.mp4`;
      openVideoModal(title, videoSrc);
    });
  });
  
  elements.closeVideoModal.addEventListener('click', closeVideo);
  
  // 社交登录事件
  elements.socialIcons.forEach(icon => {
    icon.addEventListener('click', function() {
      const platform = this.dataset.platform;
      openSocialLoginPopup(platform);
    });
  });
  
  elements.closePopup.addEventListener('click', closeSocialLoginPopup);
  
  // 平台标签切换
  elements.platformTabs.forEach(tab => {
    tab.addEventListener('click', function() {
      const platform = this.dataset.tab;
      
      // 更新标签状态
      elements.platformTabs.forEach(t => {
        t.classList.remove('active');
      });
      this.classList.add('active');
      
      // 更新内容
      elements.tabPanes.forEach(pane => {
        pane.classList.remove('active');
      });
      document.getElementById(`${platform}-tab`).classList.add('active');
    });
  });
  
  // 登录表单提交
  elements.loginForm.addEventListener('submit', function(e) {
    e.preventDefault();
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;
    
    // 简单的表单验证
    if (!username || !password) {
      alert('请输入用户名和密码');
      return;
    }
    
    // 这里应该是实际的登录逻辑
    console.log('登录成功:', username);
    closeModal(elements.loginModal);
    
    // 保存登录状态
    localStorage.setItem('isLoggedIn', 'true');
    
    // 更新用户界面为已登录状态
    updateUserProfile(username);
  });
  
  // 注册表单提交
  elements.registerForm.addEventListener('submit', function(e) {
    e.preventDefault();
    const username = document.getElementById('register-username').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm').value;
    
    // 简单的表单验证
    if (!username || !email || !password) {
      alert('请填写所有必填字段');
      return;
    }
    
    if (password !== confirmPassword) {
      alert('两次输入的密码不一致');
      return;
    }
    
    // 这里应该是实际的注册逻辑
    console.log('注册成功:', username, email);
    closeModal(elements.registerModal);
    showLoginModal();
  });
  
  // 社交账号登录
  elements.accountLoginBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      const platform = this.closest('.tab-pane').id.split('-')[0];
      const username = this.closest('.login-method').querySelector('input[type="text"]').value;
      const password = this.closest('.login-method').querySelector('input[type="password"]').value;
      
      // 简单的表单验证
      if (!username || !password) {
        alert(`请输入${platform === 'wechat' ? '微信号/手机号/QQ号' : platform === 'qq' ? 'QQ号' : '手机号/邮箱'}和密码`);
        return;
      }
      
      // 这里应该是实际的社交账号登录逻辑
      console.log(`${platform}账号登录成功:`, username);
      closeSocialLoginPopup();
      
      // 保存登录状态
      localStorage.setItem('isLoggedIn', 'true');
      
      // 更新用户界面为已登录状态
      updateUserProfile(username);
    });
  });
  
  // 侧边菜单事件
  elements.menuItems.forEach(item => {
    item.addEventListener('click', function() {
      const menuType = this.dataset.menu;
      openSidebar(menuType);
    });
  });
  
  elements.closeSidebar.addEventListener('click', closeSidebarMenu);
  elements.sidebarOverlay.addEventListener('click', closeSidebarMenu);
  
  // 底部导航事件
  elements.bottomNavItems.forEach(item => {
    item.addEventListener('click', function() {
      // 移除所有导航项的活动状态
      elements.bottomNavItems.forEach(navItem => {
        navItem.classList.remove('active');
      });
      
      // 添加当前导航项的活动状态
      this.classList.add('active');
      
      // 这里可以添加导航切换的逻辑
      const navType = this.dataset.nav;
      console.log('导航到:', navType);
    });
  });
  
  // 其他登录按钮事件
  elements.otherLoginBtn.addEventListener('click', function() {
    openSocialLoginPopup('wechat');
  });
  
  // 滚动效果
  window.addEventListener('scroll', function() {
    if (window.scrollY > 50) {
      elements.header.classList.add('scrolled');
    } else {
      elements.header.classList.remove('scrolled');
    }
  });
  
  // 设置项点击事件
  document.addEventListener('click', function(e) {
    if (e.target.closest('.setting-item .setting-value') && e.target.closest('.setting-item').querySelector('.setting-toggle')) {
      const toggle = e.target.closest('.setting-item').querySelector('.setting-toggle');
      toggle.classList.toggle('active');
    }
  });
  
  // 视频播放完成事件
  elements.videoPlayer.addEventListener('ended', function() {
    alert('视频播放完成');
  });
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
  // 缓存DOM元素
  initEventListeners();
  
  // 检查登录状态并初始化界面
  if (appState.isLoggedIn) {
    updateUserProfile('游戏达人');
  }
  
  // 初始化底部导航的活动状态
  document.querySelector('.bottom-nav .nav-item[data-nav="profile"]').classList.add('active');
  
  console.log('页面加载完成');
});